import { Storage } from './core/storage';
import { IStoreOptions } from './interfaces/store.interface';
import { storeModuleManage } from './core/module';
import Utils from './utils';

/**
 * 创建store实例
 * @param options
 * @returns
 */
const createStore = function create(options: IStoreOptions) {
	if (!options) {
		throw new Error('The create store options parameter cannot be empty');
	}

	const cacheModule: any = storeModuleManage.get(options.id);
	const { prefix, id } = storeModuleManage.getIdPrefix();

	const optionPrefix = Utils.stringUnderline(options.prefix);
	const optionsId = Utils.stringUnderline(options.id);

	// 检测id是否重复
	if (id.includes(optionsId)) {
		throw new Error(
			`Storage: The module registered using ${options.id} already exists`,
		);
	}

	// 检测prefix是否重复
	if (prefix.includes(optionPrefix)) {
		throw new Error(
			`Storage: The module's prefix ${options.prefix} is already in use`,
		);
	}

	const store = new Storage(options);
	storeModuleManage.set(store.id, store);
	return store;
};

/**
 * 获取所有模块
 * @returns
 */
const getModules = () => {
	return storeModuleManage.getAll();
};

export { createStore, getModules };
